package com.study.concurrentprogramming.memorySync;

import lombok.SneakyThrows;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description :
 * @Author : guxuemin
 * @Version : V1.0.0
 * @Date : 2022/5/10 16:15
 */
public class MemorySyncVolatile {
    public static void main(String[] args) throws InterruptedException {
        ThreadDemo1 threadDemo = new ThreadDemo1();
        new Thread(threadDemo, "t1").start();
        Lock lock = new ReentrantLock();
        while (true) {
            lock.lock();
            if (threadDemo.getFlag()) {
                System.out.println("end task");
                break;
            }
            lock.unlock();
        }
        TimeUnit.SECONDS.sleep(5);
    }
}

class ThreadDemo1 implements Runnable {
    private TestVolatile testVolatile = new TestVolatile();

    @SneakyThrows
    @Override
    public synchronized void run() {
        TimeUnit.SECONDS.sleep(3);
        Lock lock = new ReentrantLock();
        System.out.println("add lock");
//        lock.lock();
        testVolatile.setFlag(true);
        System.out.println("set flag:" + testVolatile.getFlag());
//        lock.unlock();
        System.out.println("delete lock");
    }

    public boolean getFlag() {
        return testVolatile.getFlag();
    }
}

class TestVolatile {
    private Boolean flag = false;

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    public boolean getFlag() {
        return this.flag;
    }

}